Explain Range data annotation for validation.
Explain Range data annotation for validation.
438
20-Oct-2023
Updated on 22-Oct-2023
Aryan Kumar
22-Oct-2023The Range data annotation in .NET Core is used for validation to ensure that a numeric property falls within a specified range of values. It is primarily applied to properties that represent numbers, such as integers, decimals, or floating-point numbers. The Range data annotation allows you to specify the minimum and maximum values for a property. Here's how to use it:
Import the Required Namespace:
Make sure to import the System.ComponentModel.DataAnnotations namespace, which contains the Range attribute.
Apply the Range Attribute:
Apply the Range attribute to the numeric property in your model class. You can set the Minimum and Maximum properties to define the acceptable range for the property.
In this example, the Price property is decorated with the Range attribute, specifying that the minimum value is 1 and the maximum value is 100. The ErrorMessage property is also set to provide a custom error message if the validation fails.
Display Validation Errors in Views:
In your views, you can use the ValidationMessageFor HTML helper to display validation errors for the property.
This code will display the custom error message defined in the Range attribute when the numeric value is outside the specified range.
Server-Side Validation:
In your controller action methods, you can check the ModelState.IsValid property to determine if the validation has passed. If ModelState.IsValid is false, you can handle validation errors as needed.
The Range data annotation is a powerful tool for validating that numeric properties in your model fall within a specified range of values. It provides a straightforward way to set up numeric validation rules with customizable error messages, improving data integrity and the user experience.